package io.sundial.discovery.impl;

import io.sundial.core.context.Context;
import io.sundial.core.lifecycle.exception.InitializingException;
import io.sundial.discovery.Discoverer;
import io.sundial.discovery.exception.DiscoveringException;
import io.sundial.job.Job;
import io.sundial.job.JobKey;

import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 内部加载方式的作业发现者
 *
 * @author Payne 646742615@qq.com
 * 2018/12/26 20:34
 */
public class InternalLoadingDiscoverer extends EventSupportingDiscoverer implements Discoverer {
    private final Map<JobKey, Job> jobCache = new LinkedHashMap<>();

    @Override
    protected void initializing(Context context) throws InitializingException {
        super.initializing(context);

        Map<String, Job> map = context.fetch(Job.class);
        for (Job job : map.values()) {
            jobCache.put(new JobKey(job.name(), job.group()), job);
        }
    }

    @Override
    public Job discover(String jobName, String jobGroup) throws DiscoveringException {
        Job job = jobCache.get(new JobKey(jobName, jobGroup));
        if (job == null) {
            throw new DiscoveringException("jobGroup: " + jobGroup + ", jobName: " + jobName);
        }
        return job;
    }

    @Override
    public Enumeration<Job> jobs() {
        return Collections.enumeration(jobCache.values());
    }
}
